using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Runtime.InteropServices;

namespace 吊挂备份工具
{

    public partial class Form1 : Form
    {
        private string[] specifiedTimes = { "08:44:00", "08:44:10", "08:45:00", "08:45:10", "08:43:50" };
        private int isstart = 0;
        public Form1()
        {
            InitializeComponent();
            LoadTextFromConfig();
            Exam_Type();
        }
        //保存配置
        private void button1_Click(object sender, EventArgs e)
        {
            // 获取TextBox中的文本内容  
            string textToSave = textBox1.Text;
            string textToSave2 = textBox2.Text;
            string textToSave3 = textBox3.Text;
            string textToSave4 = textBox4.Text;
            string textToSave7 = textBox5.Text;
            string textToSave8 = textBox6.Text;
            string settingValue5 = "";
            // 获取第一个RadioButton的选中值  
            if (radioButton1.Checked)
            {
                settingValue5 = radioButton1.Text;
                // 在这里处理选中值  
            }
            // 获取第二个RadioButton的选中值  
            if (radioButton2.Checked)
            {
                settingValue5 = radioButton2.Text;
                // 在这里处理选中值  
            }
            //设置列表的值
            string[] listBoxItems = new string[listBox2.Items.Count];
            for (int i = 0; i < listBox2.Items.Count; i++)
            {
                listBoxItems[i] = listBox2.Items[i].ToString();
            }
            string settingValue6 = string.Join(",", listBoxItems);

            // 将文本内容保存到配置文件中的AppSettings节  
            SaveTextToConfig(textToSave, textToSave2, textToSave3, textToSave4, settingValue5, settingValue6, textToSave7, textToSave8);
            specifiedTimes = settingValue6.Split(',');
            listBox1_show("内容已保存！");
            button6_Click(this.button6, e);
            Exam_Type();
        }
        //保存参数写入配置文件
        private void SaveTextToConfig(string settingValue, string settingValue2, string settingValue3, string settingValue4, string settingValue5, string settingValue6, string settingValue7, string settingValue8)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["key1"].Value = settingValue; // 源地址  
            config.AppSettings.Settings["key2"].Value = settingValue2; // 目标地址
            config.AppSettings.Settings["key3"].Value = settingValue3; // 间隔时间  
            config.AppSettings.Settings["key4"].Value = settingValue4; // 删除天数  
            config.AppSettings.Settings["key5"].Value = settingValue5; // 备份类型  
            config.AppSettings.Settings["key6"].Value = settingValue6; // 备份类型
            config.AppSettings.Settings["key7"].Value = settingValue7; // 备份类型  
            config.AppSettings.Settings["key8"].Value = settingValue8; // 备份类型
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
        //加载时自动执行
        private void LoadTextFromConfig()
        {
            string settingValue = ConfigurationManager.AppSettings["key1"]; // 替换 "SettingKey" 为你的配置文件中的键名  
            string settingValue2 = ConfigurationManager.AppSettings["key2"]; // 替换 "SettingKey" 为你的配置文件中的键名  
            string settingValue3 = ConfigurationManager.AppSettings["key3"]; // 替换 "SettingKey" 为你的配置文件中的键名  
            string settingValue4 = ConfigurationManager.AppSettings["key4"]; // 替换 "SettingKey" 为你的配置文件中的键名  
            string settingValue5 = ConfigurationManager.AppSettings["key5"]; // 替换 "SettingKey" 为你的配置文件中的键名
            string settingValue6 = ConfigurationManager.AppSettings["key6"]; // 替换 "SettingKey" 为你的配置文件中的键名
            string settingValue7 = ConfigurationManager.AppSettings["key7"]; // 替换 "SettingKey" 为你的配置文件中的键名
            string settingValue8 = ConfigurationManager.AppSettings["key8"]; // 替换 "SettingKey" 为你的配置文件中的键名
            if (!string.IsNullOrEmpty(settingValue))
            {
                textBox1.Text = settingValue; // 确保 textBox1 是你的文本框控件的名称  
                textBox2.Text = settingValue2; // 确保 textBox1 是你的文本框控件的名称  
                textBox3.Text = settingValue3; // 确保 textBox1 是你的文本框控件的名称  
                textBox4.Text = settingValue4; // 确保 textBox1 是你的文本框控件的名称 
                textBox5.Text = settingValue7; // 确保 textBox1 是你的文本框控件的名称  
                textBox6.Text = settingValue8; // 确保 textBox1 是你的文本框控件的名称 
                if (settingValue5 == "指定时间执行")
                {
                    radioButton2.Checked = true;
                    // 在这里处理选中值  
                }

                // 获取第二个RadioButton的选中值  
                if (settingValue5 == "间隔时间执行")
                {
                    radioButton1.Checked = true;
                    // 在这里处理选中值  
                }
            }
            //将时间写入到listbox2中
            string[] listBoxItems = settingValue6.Split(',');
            specifiedTimes = listBoxItems;
            for (int i = 0; i < listBoxItems.Length; i++)
            {
                listBox2_show(listBoxItems[i]);
            }
        }
        //手动备份操作
        private void button2_Click(object sender, EventArgs e)
        {
            // 读取源路径和目标路径  
            string sourceDirectoryPath = textBox1.Text;
            if (!Directory.Exists(sourceDirectoryPath))
            {
                listBox1_show("源地址不存在！");
                return;
            }
            string destinationDirectoryPath = textBox2.Text;
            if (!Directory.Exists(destinationDirectoryPath))
            {
                listBox1_show("目标地址不存在！");
                return;
            }
            CopyDirectory(sourceDirectoryPath, destinationDirectoryPath);
            //MessageBox.Show("复制成功！");
            listBox1_show("备份成功！");
        }


        /// <summary>
        /// 拷贝文件夹
        ///By Wang Hw  1024kb.com
        /// </summary>
        /// <param name="srcdir"></param>
        /// <param name="desdir"></param>
        private void CopyDirectory(string srcdir, string desdir)
        {
            string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1);

            string desfolderdir = desdir + "\\" + folderName;

            if (desdir.LastIndexOf("\\") == (desdir.Length - 1))
            {
                desfolderdir = desdir + folderName;
            }
            string[] filenames = Directory.GetFileSystemEntries(srcdir);

            foreach (string file in filenames)// 遍历所有的文件和目录
            {
                if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                {

                    string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
                    if (!Directory.Exists(currentdir))
                    {
                        Directory.CreateDirectory(currentdir);
                    }

                    CopyDirectory(file, desfolderdir);
                }

                else // 否则直接copy文件
                {
                    string srcfileName = file.Substring(file.LastIndexOf("\\") + 1);

                    srcfileName = desfolderdir + "\\" + srcfileName;

                    if (!Directory.Exists(desfolderdir))
                    {
                        Directory.CreateDirectory(desfolderdir);
                    }

                    File.Copy(file, srcfileName, true);
                }
            }//foreach
        }//function end

        /// <summary>
        /// 用户自定义的定时器方法，不用自带的Timer控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DefineTimer_Tick(object sender, EventArgs e)
        {
            button2_Click(this.button2, e);
            //textBox3.Text += DateTime.Now.Second.ToString() + "\n";
            //MessageBox.Show(textBox3.Text);
        }

        private void timer1_class()
        {
            //定时器间隔1秒
            int number;
            if (int.TryParse(textBox3.Text, out number))
            {
                // 转换成功，可以使用number变量  
            }
            else
            {
                // 转换失败，不能使用number变量  
                number = 7200;
            }
            timer1.Interval = number * 1000;
            if (isstart == 0)
            {
                timer1.Tick += DefineTimer_Tick;
            }
            //定时器可用
            timer1.Enabled = true;
            isstart = 1;
            //启动定时器
            timer1.Start();

        }

        private void timer1_Tick(object sender, EventArgs e)
        {

        }

        private object obj = new object();//锁
        private string lastMessage;//记录上一条历史信息
        private List<string> Messages = new List<string>();//信息集合
        private void listBox1_show(string _message)
        {

            lock (obj)
            {
                lastMessage = _message;
                string message = string.Format("[{0}]:{1}", DateTime.Now.ToString("HH:mm:ss"), _message);
                if (Messages.Count == 0)//直接插入
                {
                    Messages.Insert(0, message);
                    //SaveMessage(message);
                }
                else
                {
                    if (Messages.Count > 20) //默认信息框中最多显示20条
                        Messages.RemoveAt(Messages.Count - 1);

                    //查找头两条，是否有信息重复。存在重复，将时间刷新即可。不保存到配置文件。
                    int repeat = Messages.FindIndex(0, Messages.Count > 2 ? 2 : 1, t => t.Contains(_message));
                    //if (repeat == -1)
                    if (1 == 1)
                    {
                        Messages.Insert(0, message);
                        //SaveMessage(message);
                    }
                    else
                    {
                        Messages.RemoveAt(repeat);
                        Messages.Insert(0, message);
                    }
                }
                //绑定到listbox中显示
                listBox1.Items.Clear();
                listBox1.Items.AddRange(Messages.ToArray());
            }
        }
        //最小化按钮
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal && this.Visible == true)
            {
                this.notifyIcon1.Visible = true;//在通知区显示Form的Icon
                this.WindowState = FormWindowState.Minimized;
                this.Visible = false;
                this.ShowInTaskbar = false;//使Form不在任务栏上显示
            }
        }
        //双击托盘图标事件
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            WindowState = FormWindowState.Normal;
        }
        /// <summary>
        /// 判断是否最小化,然后显示托盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void F_Main_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon1.Visible = true;
            }
        }
        /// <summary>
        /// 确认是否退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void F_Main_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            WindowState = FormWindowState.Normal;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
            }
        }

        private void 最小化ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal && this.Visible == true)
            {
                this.notifyIcon1.Visible = true;//在通知区显示Form的Icon
                this.WindowState = FormWindowState.Minimized;
                this.Visible = false;
                this.ShowInTaskbar = false;//使Form不在任务栏上显示
            }
        }
        //自启动按钮
        private void button4_Click(object sender, EventArgs e)
        {
            string flag = "1";
            string path = Application.StartupPath;
            string keyName = path.Substring(path.LastIndexOf("\\") + 1);
            Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

            if (flag.Equals("1"))
            {
                if (Rkey == null)
                {
                    Rkey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                }
                Rkey.SetValue(keyName, path + @"\吊挂备份工具.exe");
                listBox1_show("开机自启设置成功！");
            }
            else
            {
                if (Rkey != null)
                {
                    Rkey.DeleteValue(keyName, false);
                }
            }

        }
        //保存时间配置
        private void button5_Click(object sender, EventArgs e)
        {
            listBox2_show(dateTimePicker1.Text);
        }
        private object obj2 = new object();//锁
        private string lastMessage2;//记录上一条历史信息
        private List<string> Messages2 = new List<string>();//信息集合
        private void listBox2_show(string _message)
        {

            lock (obj2)
            {
                lastMessage2 = _message;
                string message = string.Format("{0}", _message);
                if (Messages2.Count == 0)//直接插入
                {
                    Messages2.Insert(0, message);
                    //SaveMessage(message);
                }
                else
                {
                    if (Messages2.Count > 20) //默认信息框中最多显示20条
                        Messages2.RemoveAt(Messages2.Count - 1);

                    //查找头两条，是否有信息重复。存在重复，将时间刷新即可。不保存到配置文件。
                    int repeat = Messages2.FindIndex(0, Messages2.Count > 2 ? 2 : 1, t => t.Contains(_message));
                    if (repeat == -1)
                    {
                        Messages2.Insert(0, message);
                        //SaveMessage(message);
                    }
                    else
                    {
                        Messages2.RemoveAt(repeat);
                        Messages2.Insert(0, message);
                    }
                }
                //绑定到listbox中显示
                listBox2.Items.Clear();
                listBox2.Items.AddRange(Messages2.ToArray());
            }
        }
        //双击删除时间事件
        private void listBox2_DoubleClick(object sender, EventArgs e)
        {
            // 获取ListBox中当前选中的项  
            int selectedIndex = listBox2.SelectedIndex;

            // 检查是否有选中的项  
            if (selectedIndex != -1)
            {
                // 移除选中的项  
                Messages2.RemoveAt(selectedIndex);
                //绑定到listbox中显示
                listBox2.Items.Clear();
                listBox2.Items.AddRange(Messages2.ToArray());
            }
        }

        private void InitializeTimers()
        {
            timer1 = new Timer();
            timer1.Interval = 1000; // 设置定时器只触发一次  
            timer1.Tick += OnTimerElapsed; // 绑定Elapsed事件处理程序  
            timer1.Enabled = true; // 启动定时器  
        }

        private void OnTimerElapsed(object sender, EventArgs e)
        {
             foreach (var time in specifiedTimes)  
            {  
                if (DateTime.Now.ToString("HH:mm") == time)  
                {  
                    // 这里调用您想要执行的方法，例如: PerformTask();  
                    PerformTask();  
                    break; // 找到匹配的时间后跳出循环  
                }  
            }  
        }
        //执行的类型
        private void Exam_Type() {
            //获取单选框的值，判断要执行那种类型的定时器
            //定时器可用
            timer1.Enabled = false;
            timer1.Stop();
            isstart = 0;
            if (radioButton1.Checked)
            {
                //执行间隔时间执行的定时器
                timer1_class();
            }
            // 获取第二个RadioButton的选中值  
            if (radioButton2.Checked)
            {
                //执行指定时间执行的定时器
                InitializeTimers();
            }
        }
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }
        private void Form1_Closing(object sender, FormClosingEventArgs e)
        {
            this.Hide();
            e.Cancel = true;
        }
        //设置windows凭证
        private void button6_Click(object sender, EventArgs e)
        {
            string path = @""+textBox2.Text;
            int firstDoubleBackslashIndex = path.IndexOf("\\\\"); // 找到第一个双反斜杠的位置  
            int nextBackslashIndex = path.IndexOf("\\", firstDoubleBackslashIndex + 2); // 在第一个双反斜杠之后查找下一个反斜杠的位置  
            string domain = "";

            if (nextBackslashIndex != -1) // 确保找到了下一个反斜杠  
            {
                domain = path.Substring(firstDoubleBackslashIndex + 2, nextBackslashIndex - firstDoubleBackslashIndex - 2);
            }
            
            //return;                                // 获取用户输入的用户名和密码  
            string username = textBox5.Text;
            string password = textBox6.Text;

            login login = new login();
            login.CreateCred(domain, username, password);
            listBox1_show(domain+"Windows凭证设置成功"); // 输出提取的IP地址

        }
    }
}
